<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="hearder-search">
        <el-col :span="24" class="breadcrumb-container input-val-box">
          <div class="input-top">
            <el-input v-model="fromData.name" placeholder="填写教辅具" @keyup.enter.native="searchBtn"
                      size="small"></el-input>
          </div>
          <el-button type="primary" @click="searchBtn" size="small"><i class="el-icon-search"></i>搜索</el-button>
          <!--<el-button type="success" @click="submitApply" size="small">提交申请</el-button>-->
        </el-col>
        <el-col :span="24" class="breadcrumb-container">
          <div class="applyBox">
            <span class="titlebook">请选择需要申请的教辅具：</span>
            <span class="applycart" @click="showApplyCart">
              <i class="iconfont icontushu"></i>
              <span>共{{ applyBookBoxNumber.length }}件,点击查看</span>
            </span>
          </div>
        </el-col>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
              ref="multipleTable"
              :data="arryList"
              :stripe="tableStripe"
              :border="tableBorder"
              tooltip-effect="dark"
              style="width: 100%"
              header-cell-class-name="table-text-c"
              cell-class-name="table-text-c"
              @select-all="selectAll"
              @select="selectFnBox">
            <el-table-column
                type="selection"
                width="50">
            </el-table-column>
            <el-table-column
                prop="pic"
                label="缩略图"
                width="200">
              <template slot-scope="scope">
<!--                <viewerModle type="1" :imgSrc="scope.row.pic?scope.row.pic:''"></viewerModle>-->
                <ImagePreview :src="scope.row.pic" width="40px" height="40px"></ImagePreview>
              </template>
            </el-table-column>
            <el-table-column
                prop="name"
                label="教辅具名称">
            </el-table-column>
            <el-table-column
                prop="num"
                label="库存"
                width="100">
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="pageTotal"
            :page-size="pageSize"
            @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
      <div class="iframeBoxBody" v-show="iframeState_img">
        <img src="@/assets/imageAdmin/closeimg.png" alt="" @click.stop="iframeState_img=false">
        <img :src="iframeSrc_img" alt="" class="iframeBoxLine_img">
      </div>
    </div>
    <applyTeachcart :visible.sync="cartVisible" :eidtOption="applyBookBox" @detelBook="deleteFn" @submitApplyBook="submitApply" @changeInputBox="changeInput"></applyTeachcart>
  </div>
</template>

<script>
import api from '@/utils/api.js'
import applyTeachcart from '@/components/dialog/applyTeachcart.vue'

export default {
  components: {
    applyTeachcart
  },
  data() {
    return {
      cartVisible: false,
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      searchWord: '', // 搜索名称
      editLoading: false, // 编辑界面按键缓存
      addLoading: false,
      arryList: null, // 数据列表
      iframeState_img: false,
      iframeSrc_img: '',
      pageTotal: 0, // 总页数
      tieleName: '',
      page: 1,
      pageSize: 20,
      handleSelection: null, // checked选中框
      applyBookBox: {}, // 选中图书信息
      applyBookBoxInit: {}, // 本页面对应对象
      applyBookBoxNumber: [],
      fromData: {
        p: 1,
        searchWord: ''
      },
      flag: true
    }
  },
  created() {
    this.InitFn()
  },
  methods: {
    // 初始化
    InitFn() {
      let _this = this
      this.fromData.p = this.page
      this.$fetch('tools/index', this.fromData).then((response) => {
        console.log('数据：', response)
        if (response.code === 0) {
          this.arryList = response.list.data
          this.pageTotal = response.list.total
          let applyBookBoxInit = {}
          for (let i = 0; i < response.list.data.length; i++) {
            response.list.data[i].applyNumber = 1
            applyBookBoxInit[response.list.data[i].id] = response.list.data[i]
          }
          this.applyBookBoxInit = applyBookBoxInit
          _this.$nextTick(function () {
            _this.checked() // 每次更新了数据，触发这个函数即可。
          })
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 搜索
    searchBtn() {
      this.fromData.p = 1
      this.InitFn()
    },
    // 申请数量框输入
    changeInput(index) {
      console.log('input数量获取参数', index)
      console.log('已经选择的教辅具，', this.applyBookBox)
      let applyBookBox = this.applyBookBox
      if (parseInt(applyBookBox[index].applyNumber) > parseInt(applyBookBox[index].num)) {
        console.log('超过了')
        this.$message.error('超出库存')
        applyBookBox[index].applyNumber = applyBookBox[index].num
        this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
        this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      }
    },
    // 分页
    handleSizeChange(val) {
      this.page = val
      console.log(val)
      this.InitFn()
    },
    // 点击全选
    selectAll(val) {
      // 全选所有跟空值，即使页面已经选择2项
      console.log('本页面已选择得商品', this.applyBookBoxInit)
      console.log('点击全选', val)
      console.log(val) // 所有选中值
      let applyBookBox = this.applyBookBox
      if (val.length !== 0) {
        // this.handleSelection = val
        for (let i = 0; i < val.length; i++) {
          if (!applyBookBox[val[i].id]) {
            // 不存在图书
            applyBookBox[val[i].id] = val[i]
          }
        }
      } else {
        // 清除所有 arryList
        for (let i = 0; i < this.arryList.length; i++) {
          if (this.applyBookBox[this.arryList[i].id]) {
            // 存在图书删除
            delete applyBookBox[this.arryList[i].id]
          }
        }
      }
      this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      this.applyBookBoxNumber = Object.keys(this.applyBookBox)
    },
    // 点击单选
    selectFnBox(val) {
      // 选择的是当前所有的选中，还需要比对未选中项 applyBookBoxInit
      console.log('本页面的列表数据', this.applyBookBoxInit) // 已选择得选项
      console.log('点击单选', val) // 本页面点击获取到得数据,如果为空说明本页面没有选项
      console.log('本页面已经选择的this.applyBookBox几个', this.applyBookBox)
      console.log('本页面已经选择的this.applyBookBox几个', this.applyBookBox.length)
      if (this.applyBookBoxNumber >= 10) {

      } else {

      }
      let applyBookBox = this.applyBookBox

      if (val.length !== 0) {
        // 有选项 对本页面的选项进行比对
        let valBox = {}
        for (let i = 0; i < val.length; i++) {
          valBox[val[i].id] = val[i]
        }
        for (let i in this.applyBookBoxInit) {
          if (valBox[i]) {
            applyBookBox[i] = this.applyBookBoxInit[i]
          } else {
            delete applyBookBox[i]
          }
        }
      } else {
        // 清除所有 arryList
        for (let i in this.applyBookBoxInit) {
          delete applyBookBox[i]
        }
      }
      this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      console.log('this.applyBookBoxNumber:', this.applyBookBoxNumber)
    },
    // 删除图书
    deleteFn(key) {
      let applyBookBox = this.applyBookBox
      delete applyBookBox[key]
      this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      this.applyBookBoxNumber = Object.keys(this.applyBookBox)
      this.InitFn()
    },
    preveimg(e) {
      this.iframeState_img = true
      this.iframeSrc_img = e
    },
    // 提交新增，编辑书籍
    submitApply(classId) {
      // 判断新增 编辑
      console.log('申请', this.applyBookBox)
      let that = this
      if (JSON.stringify(this.applyBookBox) !== '{}') {
        let _self = this
        let teaching = []
        for (let i in this.applyBookBox) {
          let array = {}
          array.id = this.applyBookBox[i].id
          array.number = this.applyBookBox[i].applyNumber
          teaching.push(array)
        }
        if (that.flag) {
          that.flag = false
        } else {
          return
        }
        // 'tools/apply'
        this.$post(api.tools_apply_add, {
          class_id: classId,
          data: JSON.stringify(teaching)
          // admin_name: this.user_id
        }).then((response) => {
          console.log(response)
          if (response.code === 0) {
            this.applyBookBox = {} // 更新视图对象
            this.cartVisible = false
            this.applyBookBoxNumber = []
            this.$refs.multipleTable.clearSelection()
            _self.$alert('申请成功，等待管理员调配！', {
              confirmButtonText: '确定',
              callback: action => {
              }
            })

          } else {
            console.log('请求失败')
          }
          setTimeout(() => {
            that.flag = true
          }, 500)
        }).catch((err) => {
          console.log(err)
          setTimeout(() => {
            that.flag = true
          }, 500)
        })
      } else {
        this.$message.error('请选择申请的教辅具')
      }
    },
    // 设置默认选中
    checked() {
      console.log('默认选项判断', this.applyBookBox)
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          console.log('数值', i)
          this.$refs.multipleTable.toggleRowSelection(this.arryList[i], true)
        }
      }
    },
    handleClose(done) {
      done()
      this.$refs['editForm'].resetFields()
    },
    // 刷新页面
    refreshFn() {
      this.InitFn()
    },
    showApplyCart() {
      if (this.applyBookBoxNumber.length) {
        this.cartVisible = true
      } else {
        this.$message.error('请选择申请的教辅具')
      }
    }
  },
  mounted() {
  }
}
</script>

